/*
 * Copyright 2012 Google Inc. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.LiL.Wayne.Activity.activity;

import static android.view.ViewGroup.LayoutParams.MATCH_PARENT;
import static android.view.ViewGroup.LayoutParams.WRAP_CONTENT;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.List;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import com.LiL.Wayne.Activity.R;
import com.LiL.Wayne.Activity.R.drawable;
import com.LiL.Wayne.Activity.R.id;
import com.LiL.Wayne.Activity.R.layout;
import com.LiL.Wayne.Activity.activity.PlayerVideoLyrics.ImageAdapter;
import com.LiL.Wayne.Activity.activity.PlayerVideoLyrics.SharePm;
import com.LiL.Wayne.Activity.activity.PlayerVideoLyrics.ViewHolder;
import com.audamob.audasingers.constant.DeveloperKey;
import com.audamob.audasingers.model.Song;
import com.audamob.audasingers.third.youtube.YouTubeFailureRecoveryActivity;
import com.google.android.youtube.player.YouTubePlayer;
import com.google.android.youtube.player.YouTubePlayerView;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.content.res.Configuration;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.webkit.WebView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.LinearLayout.LayoutParams;

/**
 * Sample activity showing how to properly enable custom fullscreen behavior.
 * <p>
 * This is the preferred way of handling fullscreen because the default fullscreen implementation
 * will cause re-buffering of the video.
 */
public class Videos_Interface extends YouTubeFailureRecoveryActivity implements
    View.OnClickListener,
    CompoundButton.OnCheckedChangeListener,
    YouTubePlayer.OnFullscreenListener {

  private static final int PORTRAIT_ORIENTATION = Build.VERSION.SDK_INT < 9
      ? ActivityInfo.SCREEN_ORIENTATION_PORTRAIT
      : ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT;

  private LinearLayout baseLayout;
  private YouTubePlayerView playerView;
  RelativeLayout L_playerView;
  private YouTubePlayer player;
  private Button fullscreenButton;

  private View otherViews;
  private String Tag;
  private boolean fullscreen;
  
  
	String Lyrics="";
	String SongName="";
	String YoutubeUrl="";
	long Duration;
	ArrayList<Song> FavoriteList;
	Boolean PopUpOnshare=false;
	PopupWindow PopUpShare;
	Activity activity;
	class SharePm{
		String Name;
		Drawable d;
		ResolveInfo ResolveInfo;
	}
	int count=0;
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.videos_inteface);
    baseLayout = (LinearLayout) findViewById(R.id.layout);
    playerView = (YouTubePlayerView) findViewById(R.id.player);
    L_playerView=(RelativeLayout)findViewById(R.id.L_player);
    fullscreenButton = (Button) findViewById(R.id.fullscreen_button);
   
    otherViews = findViewById(R.id.other_views);

  
    // You can use your own button to switch to fullscreen too
    fullscreenButton.setOnClickListener(this);

    playerView.initialize(DeveloperKey.DEVELOPER_KEY, this);

	Bundle b=getIntent().getExtras();
	SongName=b.getString("name");
	YoutubeUrl=b.getString("Url");
	Tag=YoutubeUrl;
	YoutubeUrl="https://www.youtube.com/watch?v="+Tag;
	Duration=b.getLong("duration");
	activity=this;
	FavoriteList=new ArrayList<Song>();
	try {
		FavoriteList=restoreFavoriteList();
	} catch (IOException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	} catch (ClassNotFoundException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
	ImageView fav=(ImageView)findViewById(R.id.Favorites);
	Song ss=new Song(SongName, Duration, YoutubeUrl);
	boolean existee=false;
	for(int i =0;i<FavoriteList.size();i++){
		if(FavoriteList.get(i).getName().contains(SongName)){
			existee=true;
			break;
		}
	}
	if(existee){
		if (Build.VERSION.SDK_INT >= 16) {
		fav.setBackground(getResources().getDrawable(R.drawable.like));
		}else{
			fav.setBackgroundDrawable(getResources().getDrawable(R.drawable.like));
		}
	}
	fav.setOnClickListener(new OnClickListener() {
		
		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			Song s=new Song(SongName, Duration, YoutubeUrl);
			boolean existe=false;
			for(int i =0;i<FavoriteList.size();i++){
				if(FavoriteList.get(i).getName().contains(SongName)){
					existe=true;
					break;
				}
			}
			if(existe){
				ArrayList<Song> temp=new ArrayList<Song>();
				for(int i =0;i<FavoriteList.size();i++){
					if(FavoriteList.get(i).getName().contains(SongName)){
						
					}else{
						temp.add(FavoriteList.get(i));
					}
				
					
				}
				FavoriteList.clear();
				FavoriteList=temp;
				ImageView fav=(ImageView)findViewById(R.id.Favorites);
				if (Build.VERSION.SDK_INT >= 16) {
				fav.setBackground(getResources().getDrawable(R.drawable.dislike));
				}else{
					fav.setBackgroundDrawable(getResources().getDrawable(R.drawable.dislike));

				}
				Log.i("FavriteList","1");
				
			}else{
				FavoriteList.add(s );
				ImageView fav=(ImageView)findViewById(R.id.Favorites);
				if (Build.VERSION.SDK_INT >= 16) {
				fav.setBackground(getResources().getDrawable(R.drawable.like));
				}else{
					fav.setBackgroundDrawable(getResources().getDrawable(R.drawable.like));
				}
				Log.i("FavriteList","2");
			}
			try {
				sauvegardFavoriteList(FavoriteList);
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				Log.i("FavriteList","problem"+e.getMessage());
			}
			
		
		}
	});

	ImageView share=(ImageView)findViewById(R.id.Share);
	share.setOnClickListener(new OnClickListener() {
		
		@Override
		public void onClick(View vv) {
			// TODO Auto-generated method stub
				 
				if(!PopUpOnshare){
					PopUpOnshare=true;
		        LayoutInflater vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		        View v = vi.inflate(R.layout.dialog_options_share, null);
		        PopUpShare= new PopupWindow(v,500,500 );
		        PopUpShare.setOutsideTouchable(false);
		        PopUpShare.showAsDropDown(activity.findViewById(R.id.Share));
		        ArrayList<SharePm> ListSHare=new ArrayList<SharePm>();
		        ListView lv=(ListView)v.findViewById(R.id.ListShare);
		        String mimeType = null;
		        mimeType = "text/plain";
		        Intent shareIntent = new Intent(android.content.Intent.ACTION_SEND);
		        shareIntent.setType(mimeType);
		        
		        shareIntent.putExtra(Intent.EXTRA_TEXT, "");
		        shareIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
		     
		        final PackageManager pm = v.getContext().getPackageManager();
		        final List<ResolveInfo> activityList = pm.queryIntentActivities(shareIntent, 0);
		        for (final ResolveInfo app : activityList) {
		        	SharePm sp=new SharePm();
		        	sp.d=app.loadIcon(pm);
		        	sp.Name=app.loadLabel(pm).toString();
		        	sp.ResolveInfo=app;
		        	ListSHare.add(sp);
		        	Log.d("ShareShare"," "+app.loadLabel(pm).toString());
		          }
		        count=ListSHare.size();
		        String nom="aymennnnn";//ImageList.get(currentIndex).getNewLocation();
		        String Nomold="zvzdv" ;//ImageList.get(currentIndex).getOldLocation();
		     //   Nomold=Nomold.substring(Nomold.lastIndexOf("."), Nomold.length());
		      
		     
		        lv.setAdapter(new ImageAdapter(ListSHare));
		        
			
			
				}else{
					PopUpShare.dismiss();
					PopUpOnshare=false;
					
				}
		}
	});
	TextView namesong=  (TextView)findViewById(R.id.NameSong);
	namesong.setText(""+SongName);
    doLayout();
  }
  public class ImageAdapter extends BaseAdapter {
		private LayoutInflater mInflater;
		ArrayList<SharePm> list;

		public ImageAdapter(ArrayList<SharePm> listSHare) {mInflater = (LayoutInflater)getBaseContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			list=listSHare;
		}

		public int getCount() {
			return list.size();
		}

		public Object getItem(int position) {
			return position;
		}

		public long getItemId(int position) {
			return position;
		}

		public View getView(final int position, View convertView, ViewGroup parent) {
			final ViewHolder holder;
			if (convertView == null) {
				holder = new ViewHolder();
				
				convertView = mInflater.inflate(R.layout.item_share, null);
				
				holder.ImageFolder = (ImageView) convertView.findViewById(R.id.IconAPp);
				holder.NameFolder=(TextView)convertView.findViewById(R.id.namAPp);
				
				
				convertView.setTag(holder);
			}
			else {
				holder = (ViewHolder) convertView.getTag();
			}
			convertView.setOnClickListener(new OnClickListener(){

					@Override
					public void onClick(View v) {
						// TODO Auto-generated method stub
						int h=v.getId();
						startResolvedActivity(list.get(holder.id).ResolveInfo);
						//PopUpShare.dismiss();
					//	PopUpOnshare=false;
					//	hidecurrentImage();
					}
			});
		
			
			holder.ImageFolder.setId(position);
			holder.NameFolder.setId(position);
			
			int h=holder.ImageFolder.getId();
		
			
				holder.ImageFolder.setImageDrawable(list.get(h).d);
				
			
	
       	
				holder.NameFolder.setText(list.get(h).Name);
			holder.id = position;
			return convertView;
		}
	}
	   class ViewHolder {
		   
	  		ImageView ImageFolder;
	  		TextView NameFolder;
	  		int id;
	  		
	  	}
	   private void startResolvedActivity( ResolveInfo info) {
		    
		   
		   
		    Intent shareIntent = new Intent(android.content.Intent.ACTION_SEND);
		    String mimeType = null;
	        mimeType = "text/plain";
	        shareIntent.setType(mimeType);
	        ArrayList<Uri> uris=new ArrayList<Uri>();
	        String nom=YoutubeUrl ;//ImageList.get(currentIndex).getNewLocation();
	       
	     
	        shareIntent.putExtra(Intent.EXTRA_SUBJECT,"@Lil-Wayne-Android");
	        shareIntent.putExtra(Intent.EXTRA_SHORTCUT_NAME,"@Lil-Wayne-Android");
	        shareIntent.putExtra(Intent.EXTRA_TEXT,"@Lil-Wayne-Android  " +nom);
	        shareIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
	        final Intent resolvedIntent = new Intent(shareIntent);
	        ActivityInfo ai = info.activityInfo;
	     
	        resolvedIntent.setComponent(new ComponentName(ai.applicationInfo.packageName, ai.name));
	        startActivity(resolvedIntent);
	     
	    
	   }
  @Override
  public void onInitializationSuccess(YouTubePlayer.Provider provider, YouTubePlayer player,
      boolean wasRestored) {
    this.player = player;
    setControlsEnabled();
    // Specify that we want to handle fullscreen behavior ourselves.
    player.addFullscreenControlFlag(YouTubePlayer.FULLSCREEN_FLAG_CUSTOM_LAYOUT);
    player.setOnFullscreenListener(this);
    if (!wasRestored) {
      player.cueVideo(Tag);
    }
    this.player.setShowFullscreenButton(true);
    player.setShowFullscreenButton(true);
  }

  @Override
  protected YouTubePlayer.Provider getYouTubePlayerProvider() {
    return playerView;
  }

  @Override
  public void onClick(View v) {
    player.setFullscreen(!fullscreen);
  }

  @Override
  public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
    int controlFlags = player.getFullscreenControlFlags();
    if (isChecked) {
      // If you use the FULLSCREEN_FLAG_ALWAYS_FULLSCREEN_IN_LANDSCAPE, your activity's normal UI
      // should never be laid out in landscape mode (since the video will be fullscreen whenever the
      // activity is in landscape orientation). Therefore you should set the activity's requested
      // orientation to portrait. Typically you would do this in your AndroidManifest.xml, we do it
      // programmatically here since this activity demos fullscreen behavior both with and without
      // this flag).
      setRequestedOrientation(PORTRAIT_ORIENTATION);
      controlFlags |= YouTubePlayer.FULLSCREEN_FLAG_ALWAYS_FULLSCREEN_IN_LANDSCAPE;
    } else {
      setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR);
      controlFlags &= ~YouTubePlayer.FULLSCREEN_FLAG_ALWAYS_FULLSCREEN_IN_LANDSCAPE;
    }
    player.setFullscreenControlFlags(controlFlags);
  }

  private void doLayout() {
	  LinearLayout.LayoutParams L_playerParams =
		        (LinearLayout.LayoutParams) L_playerView.getLayoutParams();
    RelativeLayout.LayoutParams playerParams =
        (RelativeLayout.LayoutParams) playerView.getLayoutParams();
    if (fullscreen) {
      // When in fullscreen, the visibility of all other views than the player should be set to
      // GONE and the player should be laid out across the whole screen.
      
    	L_playerParams.width = LayoutParams.MATCH_PARENT;
        L_playerParams.height = LayoutParams.MATCH_PARENT;
    	playerParams.width = LayoutParams.MATCH_PARENT;
        playerParams.height = LayoutParams.MATCH_PARENT;

      otherViews.setVisibility(View.GONE);
    } else {
      // This layout is up to you - this is just a simple example (vertically stacked boxes in
      // portrait, horizontally stacked in landscape).
      otherViews.setVisibility(View.VISIBLE);
      ViewGroup.LayoutParams otherViewsParams = otherViews.getLayoutParams();
      if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
       
    	  L_playerParams.width = otherViewsParams.width = 0;
          L_playerParams.height = MATCH_PARENT;
          L_playerParams.weight = 3;
          otherViewsParams.height = MATCH_PARENT;
         otherViewsParams.width = 0;
       
         playerParams.height = WRAP_CONTENT;
         playerParams.width=MATCH_PARENT;
        playerParams.addRule(RelativeLayout.CENTER_VERTICAL);
       
       
        baseLayout.setOrientation(LinearLayout.HORIZONTAL);
      }
      setControlsEnabled();
    }
  }

  private void setControlsEnabled() {
   
    fullscreenButton.setEnabled(player != null);
  }

  @Override
  public void onFullscreen(boolean isFullscreen) {
    fullscreen = isFullscreen;
    doLayout();
  }

  @Override
  public void onConfigurationChanged(Configuration newConfig) {
    super.onConfigurationChanged(newConfig);
    doLayout();
  }
  @Override
	public void onBackPressed() {
		// TODO Auto-generated method stub
	  
	  if(PopUpOnshare){
			 PopUpShare.dismiss();
			 PopUpOnshare=false;
		 }else{
		if(!fullscreen){
			super.onBackPressed();
		}else{
			fullscreen=false;
			this.player.setFullscreen(false);
		}
		 }
	}
@Override
	protected void onStart() {
		// TODO Auto-generated method stub
		super.onStart();
		ThreadLoad threadLoad=new ThreadLoad(handlerLoad);
		threadLoad.start();
	}
TextView TextLyrics;
final Handler handlerLoad = new Handler() {


    public void handleMessage(Message msg) {
    	try{
    		TextLyrics=(TextView)findViewById(R.id.TextLyrics);
			  String lyric=msg.getData().toString();
			  String cast="Bundle[{url=";
	    	
	    		 lyric=lyric.substring(cast.length()+1, lyric.length()-3);
	    	
			 TextLyrics.setText(lyric);
    	}catch (Exception e) {
			// TODO: handle exception
		}
		    	
    }
};
private class ThreadLoad extends Thread {	
 Handler mHandler;

ThreadLoad(Handler h) {
    mHandler = h;
}
public void run() {
	 try {
		currentThread().sleep(500);
	} catch (InterruptedException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
   String UrlBack="";
   try {
		
   String SongNamee=SongName.replace(" ", "_");
 
   String UrlLyrics="http://lyrics.wikia.com/Lil_Wayne:"+SongNamee;
   org.jsoup.nodes.Document doc = Jsoup.connect(UrlLyrics).get();
		Elements content = doc.getElementsByTag("div");
		//Elements links = content.getElementsByTag("a");
		for (Element link : content) {
		  String linkHref = link.className();
		  if(linkHref.equals("lyricbox")){
			Log.d("Lyrics","lyrics= "+linkHref);
			 String linkText = link.text();
			try {
			linkText=linkText.substring(0, linkText.lastIndexOf("Send "));
		} catch (Exception e) {
			// TODO: handle exception
		}
		try {
			linkText=linkText.substring(0, linkText.lastIndexOf("</lyrics> "));
		} catch (Exception e) {
			// TODO: handle exception
		}
		try {
			linkText=linkText.substring( linkText.indexOf("to your Cell")+12,linkText.length());
		} catch (Exception e) {
			// TODO: handle exception
		}
		try {
			linkText=linkText.substring(0, linkText.lastIndexOf("we are not licensed"));
		} catch (Exception e) {
			// TODO: handle exception
		}
		try {
			linkText=linkText.replace(",", "\n\n");
		} catch (Exception e) {
			// TODO: handle exception
		}
			 UrlBack=linkText;
		
		  }
		}

	} catch (Exception e) {
		// TODO: handle exception
	}
	Message msg = mHandler.obtainMessage();
	Bundle b = new Bundle();
	b.putString("url", ""+UrlBack);
	msg.setData(b);
	mHandler.sendMessage(msg);

}

}
public ArrayList<Song> restoreFavoriteList() throws IOException, ClassNotFoundException {
	FileInputStream fin = new FileInputStream(getCacheDir().getAbsolutePath()+"/favoritesong");
	ObjectInputStream in = new ObjectInputStream(fin);
	ArrayList<Song> object = (ArrayList<Song>)in.readObject();
	in.close();
	return object;
}
public void sauvegardFavoriteList(ArrayList<Song> s) throws IOException {
	FileOutputStream fout = new FileOutputStream(getCacheDir().getAbsolutePath()+"/favoritesong");
	ObjectOutputStream out = new ObjectOutputStream(fout);
	
	out.writeObject(s);
	out.close();
}
@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
	try {
		player.release();
	} catch (Exception e) {
		// TODO: handle exception
	}
	
		super.onDestroy();
	}
}
